<template>
  <div class="quota-container">
    <!-- 会员套餐信息卡片 -->
    <el-card class="package-card">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon">
            <Wallet />
          </el-icon>
          <span>会员套餐信息</span>
        </div>
      </template>

      <div class="package-info">
        <div class="info-header">
          <div class="package-type">
            <span class="type-label">{{ packageInfo.packageType }}</span>
            <span class="validity-period">
              有效期：{{ formatDate(packageInfo.startTime) }} 至 {{ formatDate(packageInfo.endTime) }}
            </span>
          </div>
          <div class="actions">
            <el-button type="primary" @click="goToRecharge">立即充值</el-button>
            <el-tag :type="getRemainingDays > 30 ? 'success' : getRemainingDays > 7 ? 'warning' : 'danger'">
              剩余 {{ getRemainingDays }} 天
            </el-tag>
          </div>
        </div>

        <div class="quota-progress">
          <div class="progress-header">
            <span>额度使用情况</span>
            <span class="quota-numbers">
              已用 {{ packageInfo.usedQuota }} / 总额 {{ packageInfo.totalQuota }}
            </span>
          </div>
          <el-progress :percentage="getQuotaPercentage"
            :status="getQuotaPercentage >= 90 ? 'exception' : getQuotaPercentage >= 70 ? 'warning' : 'success'" />
        </div>
      </div>
    </el-card>

    <!-- 充值记录卡片 -->
    <el-card class="recharge-card">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon">
            <Tickets />
          </el-icon>
          <span>充值记录</span>
        </div>
      </template>

      <el-table :data="rechargeRecords" stripe style="width: 100%">
        <el-table-column prop="transferTime" label="充值时间" min-width="200">
          <template #default="{ row }">
            {{ formatDateTime(row.transferTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" min-width="180">
          <template #default="{ row }">
            {{(row.phone) }}
          </template>
        </el-table-column>
        <el-table-column label="套餐价格" min-width="180" align="center">
          <template #default="{ row }">
            <span class="price" v-if="row.packageDetails">￥{{ row.packageDetails.price }}</span>
            <span v-else class="price">--</span>
          </template>
        </el-table-column>
        <el-table-column label="充值额度" min-width="180" align="center">
          <template #default="{ row }">
            <span class="points" v-if="row.packageDetails">{{ row.packageDetails.points }}点</span>
            <span v-else class="points">--</span>
          </template>
        </el-table-column>
        <el-table-column label="持续时间" min-width="180" align="center">
          <template #default="{ row }">
            <el-tag size="small" type="success" v-if="row.packageDetails">{{ row.packageDetails.duration }}</el-tag>
            <el-tag size="small" type="info" v-else>未知</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <div class="empty-text" v-if="!rechargeRecords.length">
        暂无充值记录
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue';
import { Wallet, Tickets } from '@element-plus/icons-vue';
import dayjs from 'dayjs';
import { getUserPackageApi, getRechargeRecordsApi } from '@/api/quota';
import { ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';

const router = useRouter();
const route = useRoute();

// 会员套餐信息
const packageInfo = ref({
  packageType: '无套餐',
  totalQuota: 0,
  usedQuota: 0,
  startTime: '',
  endTime: ''
});

// 充值记录
const rechargeRecords = ref([]);

// 获取套餐信息
const fetchPackageInfo = async () => {
  try {
    const response = await getUserPackageApi();
    if (response.data.code === 201) {
      // 没有套餐信息，使用默认值
      packageInfo.value = {
        packageType: '无套餐',
        totalQuota: 0,
        usedQuota: 0,
        startTime: '',
        endTime: ''
      };
      return;
    }
    packageInfo.value = response.data.data;
  } catch (error) {
    ElMessage.error('请求失败，请检查网络或登录状态');
    console.error('Error fetching package info:', error);
  }
};

// 获取充值记录
const fetchRechargeRecords = async () => {
  try {
    const response = await getRechargeRecordsApi();
    if (response.data.code === 201) {
      ElMessage.error(response.data.data)
      return
    }
    // 确保每条记录的packageDetails存在且只包含后端支持的字段
    rechargeRecords.value = response.data.data.map(record => {
      if (record.packageDetails) {
        // 只保留后端支持的字段
        const { price, points, duration } = record.packageDetails;
        record.packageDetails = { price, points, duration };
      }
      return record;
    });
  } catch (error) {
    ElMessage.error('请求失败，请检查网络或登录状态');
    console.error('Error fetching recharge records:', error);
  }
};

// 刷新所有数据
const refreshAllData = () => {
  fetchPackageInfo();
  fetchRechargeRecords();
};

// 计算属性
const getQuotaPercentage = computed(() => {
  return packageInfo.value.totalQuota > 0
    ? Math.round((packageInfo.value.usedQuota / packageInfo.value.totalQuota) * 100)
    : 0;
});

const getRemainingDays = computed(() => {
  const end = dayjs(packageInfo.value.endTime);
  const now = dayjs();
  return end.diff(now, 'day');
});

// 格式化日期
const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD') : '';
};

// 格式化完整日期时间
const formatDateTime = (datetime) => {
  return datetime ? dayjs(datetime).format('YYYY-MM-DD HH:mm:ss') : '';
};



// 前往充值页面
const goToRecharge = () => {
  router.push('/main/recharge');
};

// 监听路由变化，当进入此页面时刷新数据
watch(() => route.fullPath, (newPath) => {
  if (newPath === '/main/quota') {
    refreshAllData();
  }
}, { immediate: true });

// 组件挂载时获取数据
onMounted(() => {
  refreshAllData();
});

// 在组件销毁前清理所有可能的监听器或定时器
onBeforeUnmount(() => {
  // 这里添加需要清理的逻辑
});
</script>

<style lang="scss" scoped>
.quota-container {
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 24px;

  .package-card {
    border-radius: 12px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);

    :deep(.el-card__header) {
      padding: 20px 24px;
      border-bottom: 1px solid #e6e8eb;
    }
  }

  .card-header {
    display: flex;
    align-items: center;
    gap: 12px;

    .header-icon {
      font-size: 24px;
      color: #1a73e8;
    }

    span {
      font-size: 18px;
      font-weight: 600;
      color: #1f2937;
    }
  }

  .package-info {
    padding: 20px;

    .info-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;

      .package-type {
        display: flex;
        flex-direction: column;
        gap: 4px;

        .type-label {
          font-size: 24px;
          font-weight: 600;
          color: #1f2937;
        }

        .validity-period {
          font-size: 14px;
          color: #64748b;
        }
      }

      .actions {
        display: flex;
        align-items: center;
        gap: 12px;
      }
    }

    .quota-progress {
      .progress-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 12px;
        color: #64748b;
        font-size: 14px;

        .quota-numbers {
          color: #1f2937;
          font-weight: 500;
        }
      }
    }
  }

  .recharge-card {
    border-radius: 12px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);

    :deep(.el-card__header) {
      padding: 20px 24px;
      border-bottom: 1px solid #e6e8eb;
    }

    .package-details {
      display: flex;
      align-items: center;
      gap: 12px;

      .points {
        color: #1f2937;
        font-weight: 500;
      }

      .divider {
        color: #e5e7eb;
      }

      .price {
        color: #10b981;
        font-weight: 500;
      }
    }

    .empty-text {
      text-align: center;
      color: #64748b;
      padding: 32px 0;
      font-size: 14px;
    }
  }

  :deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;

    th {
      background-color: #f8fafc;
      font-weight: 600;
      color: #1f2937;
      padding: 16px;
      text-align: center !important;
    }

    td {
      padding: 16px;
    }

    .el-table__empty-block {
      min-height: 160px;
    }
  }
}

.price {
  color: #10b981;
  font-weight: 500;
  font-size: 15px;
}

.points {
  color: #1f2937;
  font-weight: 500;
  font-size: 15px;
}
</style>